import {
	decrypt,
	encrypt
} from 'crypto-js/aes';
import Base64 from 'crypto-js/enc-base64';
import {
	parse
} from 'crypto-js/enc-utf8';
import UTF8 from 'crypto-js/enc-utf8';
import md5 from 'crypto-js/md5';
import ECB from 'crypto-js/mode-ecb';
import pkcs7 from 'crypto-js/pad-pkcs7';

/**
 * AES 加密解密
 */
export class AesEncryption {
	constructor(opt = {}) {
		const {
			key,
			iv
		} = opt;
		if (key) {
			this.key = parse(key);
		}
		if (iv) {
			this.iv = parse(iv);
		}
	}

	get getOptions() {
		return {
			mode: ECB,
			padding: pkcs7,
			iv: this.iv,
		};
	}

	encryptByAES(cipherText) {
		return encrypt(cipherText, this.key, this.getOptions).toString();
	}

	decryptByAES(cipherText) {
		return decrypt(cipherText, this.key, this.getOptions).toString(UTF8);
	}
}

/**
 * Base64加密
 * @param cipherText
 */
export function encryptByBase64(cipherText) {
	return UTF8.parse(cipherText).toString(Base64);
}

/**
 * Base64解密
 * @param cipherText
 */
export function decodeByBase64(cipherText) {
	return Base64.parse(cipherText).toString(UTF8);
}

/**
 * MD5加密
 * @param password
 */
export function encryptByMd5(password) {
	return md5(password).toString();
}